package com.jindianjichi.wx.handler;

import com.jindianjichi.wx.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ReceiveTextHandler implements WxChatMsgHandler{
    public static final String KEY_WORD="验证码";
    private static final String LOGIN_PREFIX = "loginCode";
    @Resource
    private RedisUtil redisUtil;
    @Override
    public WxChatMsgTypeEnum getMsgType() {

        return WxChatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String,String> messageMap) {
        log.info("触发文本事件");
        String fromUserName = messageMap.get("FromUserName");
        String toUserName = messageMap.get("ToUserName");
        String content = messageMap.get("Content");
        if (!"验证码".equals(content)){
            return "";
        }
        Random random=new Random();
        int num = random.nextInt(10000);
        String numKey = redisUtil.buildKey( LOGIN_PREFIX,String.valueOf(num));
        redisUtil.setNx(numKey,fromUserName,5L, TimeUnit.MINUTES);
        String receiveContent="您当前的验证码是!："+num+":5分钟内有效";
        String replyContent="<xml>\n" +
                "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
                "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                "  <CreateTime>1348831860</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA["+receiveContent+"]]></Content>\n" +
                "</xml>";
        return replyContent;
    }
}
